package com.sh.data.engine.domain.shims.kafka.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.List;

public class SocketUtil {

    private static final int DEFAULT_SOCKET_TIMEOUT = 1;

    public static List<Pair<String, Integer>> parseHostAndPort(String address, Integer defaultPort) {
        if (StringUtils.isBlank(address)) {
            throw new IllegalArgumentException();
        }

        String[] array = StringUtils.split(address, ",");
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException();
        }

        List<Pair<String, Integer>> list = new LinkedList<>();
        for (String str : array) {
            if (StringUtils.isBlank(str)) {
                continue;
            }
            String host = str;
            Integer port = defaultPort;
            if (StringUtils.contains(str, ":")) {
                host = StringUtils.substringBefore(str, ":");
                try {
                    port = Integer.parseInt(StringUtils.trim(StringUtils.substringAfter(str, ":")));
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(e);
                }
            }
            host = StringUtils.trim(host);
            list.add(ImmutablePair.of(host, port));
        }
        return list;
    }

    public static void testSocketConnection(List<Pair<String, Integer>> list, Integer timeout)
        throws IOException, IllegalArgumentException {
        if (CollectionUtils.isEmpty(list)) {
            throw new IllegalArgumentException();
        }
        for (Pair<String, Integer> pair : list) {
            String host = pair.getKey();
            Integer port = pair.getValue();
            testSocketConnection(host, port, timeout);
        }
    }

    public static void testSocketConnection(String host, Integer port, Integer timeout)
        throws IOException, IllegalArgumentException {
        if (StringUtils.isBlank(host) || port == null || port <= 0) {
            throw new IllegalArgumentException();
        }
        if (timeout == null || timeout <= 0) {
            timeout = DEFAULT_SOCKET_TIMEOUT;
        }
        long start = System.currentTimeMillis();
        try (Socket socket = new Socket()) {
            SocketAddress address = new InetSocketAddress(host, port);
            socket.connect(address, timeout * 1000);
        } catch (IOException e) {
            throw new IOException(
                "网络请求错误(" + getTimeDiff(start) + "ms)，请检查" + host + "的端口" + port + "是否可连接", e);
        } catch (SecurityException e) {
            throw new SecurityException("系统安全配置有误，请联系管理员", e);
        }
    }

    private static long getTimeDiff(long start) {
        return System.currentTimeMillis() - start;
    }
}
